import axios from 'axios';
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { getToken } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';

function isBlob(res: any) {
  return res.request.responseType === 'blob' || res.data instanceof Blob;
};

export interface HttpResponse<T = any> {
  msg?: string;
  code?: number;
  data?: T;
}
export type MethodType = 'get' | 'post' | 'put' | 'delete';

const baseURL = import.meta.env.VITE_API_BASE_URL;

const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000,
});

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (isBlob(response)) {
      return response;
    }
    const res = response.data;

    if (res.code === 200) {
      return res;
    }
    if (res.code === 401) {
      Message.warning('登录超时');
    }
    Message.error(res.msg);
    return Promise.reject(new Error(res.msg || 'Error'));
  },
  (error) => {
    Message.error(error.msg);
    return Promise.reject(error);
  }
);

// 下载文件 默认下载excel
export async function downloadFile(url: string, params: any, name: string | undefined, type: string | undefined | null = '.xlsx') {
  async function getBlobDownload() {
    const postRes = await instance.post(
      baseURL + url,
      params,
      {
        responseType: 'blob',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      }
    );
    return postRes;
  }
  const response: any = await getBlobDownload();
  if (isBlob(response)) {
    let myurl = window.URL.createObjectURL(new Blob([response.data], {
      type:
        type === '.docx'
          ? 'application/msword'
          : type === '.zip'
            ? 'application/zip'
            : type === '.xlsx'
              ? 'application/vnd.ms-excel'
              : 'application/octet-stream', // 默认类型
    }));

    // 创建一个a标签用于下载
    let a = document.createElement('a');
    a.style.display = 'none';
    a.href = myurl;
    a.download = `${name || '文件'}${type}`;
    // 将a标签添加到文档中（虽然它不会显示）
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(a.href); // 释放URL 对象
    document.body.removeChild(a); // 移除<a>标签
  }
}

type paramsData<T = any> = {
  params?: T;
  data?: T;
};

const request = <T>(
  method: MethodType,
  url: string,
  params?: paramsData | any,
  config?: any
) => {
  const data = instance[method]<any, HttpResponse<T>>(url, Array.isArray(params) ? [...params] : {
    ...params,
  }, config);
  return data;
};

export const upload = <T>(
  url: string,
  formData?: FormData,
) => {
  const data = instance.post<any, HttpResponse<T>>(url, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
  return data;
};

export default request;
